'use strict';
dataloaderApp.controller ('SalesForceProfileCtrl' , [ '$scope', '$rootScope', '$route','$routeParams' , '$location',  '$filter' , 'salsforceService'
		, function ( $scope, $rootScope, $route, $routeParams , $location,  $filter , salsforceService) {

	$scope.profile = new DataLoader.Profile();
	$scope.salesForceProfile = new DataLoader.SalesForceProfile();
	$scope.profiles = {};
	$scope.enviroment = {name: ''};
	$scope.enabledProfile = new DataLoader.Profile();
	
	$scope.addingAction = false;
	
	$scope.$on ('exception', function(event,args) {
		$scope.exceptionInfo = { message : args.localMessage };
		$scope.hasError = true;
		setTimeout(function () {   
   			$scope.hasError = false;
   			$scope.$apply();
		},10000);
	});	

	$scope.$on('success', function (event,args) {
		$scope.hasSuccess = true;
		setTimeout(function () {   
   			$scope.hasSuccess = false;
   			$scope.$apply();
		},10000);

	});
	
	$scope.getEnabledProfile = function (){
		salsforceService.getEnabledProfile().then (function (response){
			
			$scope.enabledProfile = response;	
			
			setTimeout(function () {   
				$scope.getEnabledProfile();
	   			$scope.$apply();
			},60000);
			
		});		
	}
	
	$scope.getAddTemplate = function () {
		if (!$scope.addingAction) return "";
		return "partials/salesforce-profile/add.html";
	};
	
	$scope.$watch('salesForceProfile.connection', function(newValue, oldValue) {

		if (newValue === oldValue) { return; } 
		
		$scope.profile = $scope.salesForceProfile.createProfileFromTemplate($scope.salesForceProfile.connection);

	});	

	$scope.getAddTemplate = function () {
		if (!$scope.addingAction) return "";
		return "partials/salesforce-profile/add.html";
	}

	$scope.addAction =function () {
		$scope.addingAction = true;
	}
	
	$scope.allProfiles = function () {
		salsforceService.findAll ().then(function (response) {
			$scope.profiles = response;
		});
	};

	$scope.add = function () {
		if (!$scope.profile) return;

		salsforceService.add ($scope.profile).then(function(respone) {
			$scope.addingAction = false;
			
			$rootScope.$broadcast('success', {	message : 'Usuario Adicionado com sucesso'	});
			
			$scope.allProfiles();
			
			$scope.getEnabledProfile ();
			
		});
	};
 	
			
}]);
